#include"Heap.h"

void HpInit(Hp* php)
{
	assert(php);
	HpDataType* ret = (HpDataType*)malloc(sizeof(HpDataType) * 4);
	if (ret == NULL)
	{
		perror("malloc fail");
		return;
	}
	php->a = ret;
	php->capacity = 4;
	php->size = 0;
}

void DestroyHeap(Hp* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = 0;
	php->size = 0;
}

void Swap(HpDataType* p1, HpDataType* p2)
{
	HpDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void HeapPush(Hp* php, HpDataType x)
{
	assert(php);
	if (php->capacity == php->size)
	{
		//HPDataType* tmp = (HPDataType*)realloc(php->a, sizeof(HPDataType) * php->capacity*2);
		HpDataType* tmp = (HpDataType*)realloc(php->a, sizeof(HpDataType) * php->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = tmp;
		php->capacity *= 2;
	}
	php->a[php->size++] = x;
	AdjustUp(php->a, php->size - 1);
}

bool HeapEmpty(Hp* php)
{
	assert(php);
	return php->size == 0;
}

void AdjustDown(HpDataType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child])
		{
			++child;
		}
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}




void HeapPop(Hp* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	AdjustDown(php->a, php->size, 0);
}


HpDataType HeapTop(Hp* php)
{
	assert(php);
	return php->a[0];
}

int HeapSize(Hp* php)
{
	assert(php);
	return php->size;
}

void AdjustUp(HpDataType* a, int child) {
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}




